﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Transport
{
    class Connection
    {
        TcpClient client;
        // The thread that will send information to the client
        private Thread thrSender;
        private StreamReader srReceiver;
        private StreamWriter swSender;
        private string strResponse;

        // The constructor of the class takes in a TCP connection
        public Connection(TcpClient client)
        {
            this.client = client;
            // The thread that accepts the client and awaits messages
            thrSender = new Thread(AcceptClient);
            // The thread calls the AcceptClient() method
            thrSender.Start();
        }

        // Occures when a new client is accepted
        private void AcceptClient()
        {
            srReceiver = new StreamReader(client.GetStream());
            // Keep waiting for a message from the user
            while ((strResponse = srReceiver.ReadLine()) != null)
            {
                // Otherwise send the message to all the other users
                Server.SendMessage(strResponse);
                
            }
        }

        public void CloseConnection()
        {
            // Close the currently open objects
            client.Close();
            srReceiver.Close();
            swSender.Close();
        }
    }
}
